<template>
    <basic-container :btnFlag=true>
        <div class="card-border">
            <!--<process-view-simple-planning-register :active="3" />-->
            <process-view-simple-register-flowsheet :taskId="taskId"/>
            <card-header :header-data="headerData"></card-header>
            <activiti-action ref="action"
                             :task-id="taskId"
                             @confirm="submitConfirm"
                             v-model="form">
                <template slot="buttonRight">

                </template>
                <template slot="formHeader">
                    <el-form ref="form"
                             label-position="left"
                             label-width="100px"
                             v-if="form.action == 'agree'"
                             :model="form"
                             :rules="formRules">
                        <el-form-item v-if="planningRegisterInfo.category != 'D'"
                                      label="规划等级"
                                      prop="planningRank">
                            <el-select v-model="form.planningRank"
                                       placeholder="请选择规划等级">
                                <el-option v-for="item in planningRankDic"
                                           :key="item.value"
                                           :label="item.label"
                                           :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item v-if="planningRegisterInfo.category == 'D'"
                                      label="是否上报政府"
                                      prop="needReport">
                            <el-select v-model="form.needReport">
                                <el-option label="是" :value="true"/>
                                <el-option label="否" :value="false"/>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="编制要求"
                                      prop="requirement">
                            <el-input v-model="form.requirement"
                                      type="textarea"
                                      rows="3"
                                      placeholder="请输入编制要求">
                            </el-input>
                        </el-form-item>
                    </el-form>
                </template>
            </activiti-action>
            <el-tabs class="bs-tab"
                     v-model="activeName"
                     type="card">
                <el-tab-pane label="申请信息"
                             name="first">
                    <register-detail class="register-detail"
                                     :id="registerinfoId"/>
                </el-tab-pane>
                <el-tab-pane label="办理过程"
                             name="second">
                    <process-handle-history :task-id="taskId"/>
                </el-tab-pane>
                <el-tab-pane label="会商意见"
                             name="third">
                    <el-tabs v-model="topicActiveName" style="padding: 12px;margin-top:20px;" v-if="msgFlag">
                        <el-tab-pane
                                :label="item.deptName"
                                :name="String(item.topicId)"
                                v-for="(item,index) in msgList"
                                :key="index">
                            <msg-nobtn :msg-data="msgDataListTemp"></msg-nobtn>
                            <el-pagination
                                    @size-change="sizeChange"
                                    @current-change="onLoad"
                                    :current-page="pageTemp.currentPage"
                                    :page-size="pageTemp.pageSize"
                                    :total="pageTemp.total"
                                    :page-sizes="[10, 20, 30, 40 ,50 ,100]"
                                    layout="total, sizes, prev, pager, next, jumper"
                                    v-if="msgDataListTemp.length>0"
                                    class="paginationcss">
                            </el-pagination>
                            <div v-if="msgDataListTemp.length<=0"
                                 style="text-align: center;font-size: 18px;margin-top: 28px;">
                                暂无数据
                            </div>
                        </el-tab-pane>
                    </el-tabs>
                    <div v-if="!msgFlag" style="text-align: center;font-size: 18px;margin-top: 20px;">
                        暂无数据
                    </div>
                </el-tab-pane>
                <el-tab-pane label="会办流程"
                             name="fourth">
                    <jointly-handle-div v-if="processId != null"
                                        type="JOINTLY_HANDLE_TYPE_REGISTER_FGW"
                                        :business-key="registerinfoId"
                                        :process-id="processId">
                    </jointly-handle-div>
                </el-tab-pane>

            </el-tabs>
        </div>
    </basic-container>
</template>

<script>
    import processViewSimplePlanningRegister from '@/components/activiti/process-view/simple/planning-register'
    import activitiAction from "@/components/activiti/action"
    import registerDetail from "@/components/registerinfo/registerDetail"
    import {taskComplete, getTaskInfo} from "@/api/activiti/monitor";
    import processHandleHistory from "@/components/activiti/history/processHandleHistory";
    import {listProcessVariables} from "@/api/activiti/monitor";
    import {projectDetail} from "@/api/planning/project";
    import {PROJECT_DIC} from '@/const/dict'
    import topicRelateBtn from "@/components/activiti/topic-relate-button/topicRelateBtn";

    import {mapGetters} from "vuex"
    import getDetailData from "@/mixins/getDetailData";
    import chatMsg from '@/components/bostech/chat-msg'
    import MsgNobtn from "../../../components/bostech/msg-nobtn";
    import jointlyHandleDiv from "@/components/activiti/jointly-handle-button/jointlyHandleDiv";
    import {messagePage} from '@/api/planning/message'
    import {getfileinfopage} from "@/api/system";

    let stageMap = {
        'A': 0,
        'B': 1,
        'C': 2,
        'D': 3,
        'E': 5,
        'F': 6,
        'G': 6,
        'H': 8,
        'I': 9
    };
    export default {
        name: "planningRegisterFgwCheck",
        mixins: [getDetailData()],
        components: {
            processViewSimplePlanningRegister,
            activitiAction,
            registerDetail,
            processHandleHistory,
            topicRelateBtn,
            jointlyHandleDiv,
            MsgNobtn,
            chatMsg
        },
        watch: {
            'topicActiveName'(val) {
                this.topicIdTemp = val;
                this.onLoadFortabs();
            }
        },
        data() {
            return {
                headerData: {
                    title: "主办处长审核"
                },
                activeName: 'first',
                taskId: null,
                processId: null,
                registerinfoId: null,
                msgListTemp: [],
                msgList: [],
                topicActiveName: null,
                jointlyHandleList: null,
                msgFlag: false,
                topicIdTemp: 0,
                msgDataListTemp: [],
                page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 10 // 每页显示多少条
                },
                pageTwo: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 10 // 每页显示多少条
                },
                pageTemp: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 10 // 每页显示多少条
                },


                form: {},
                formRules: {
                    needReport: [
                        {required: true, message: "请选择是否需要上报政府", trigger: "blur"}
                    ],
                    planningRank: [
                        {required: true, message: "请选择规划等级", trigger: "blur"}
                    ],
                },
                planningRankDic: PROJECT_DIC.PLANNING_RANK,
                planningRegisterInfo: null
            }
        },
        created() {
            this.getDetailData();
            this.init();
            this.taskId = this.$route.params.taskId;
            this.registerinfoId = this.$route.query.registerinfoId;
            this.getTaskInfo()
        },
        computed: mapGetters([
            "userInfo"
        ]),
        methods: {
            getTaskInfo() {
                getTaskInfo(this.taskId).then((res) => {
                    let taskInfo = res.data.data;
                    if (taskInfo != null) {
                        this.processId = taskInfo.processId;
                    }
                });
            },
            init() {
                this.taskId = this.$route.params.taskId;
                this.registerinfoId = this.$route.query.registerinfoId;
                this.getPlanningRegisterInfo();
                this.getProcessVariables();
            },
            getProcessVariables() {
                listProcessVariables({taskId: this.taskId}).then((res) => {
                    let processVariables = res.data.data;
                    if (processVariables != null) {
                        this.form.planningRank = processVariables.planningRank;
                        this.form.requirement = processVariables.requirement;
                    }
                });
            },
            getPlanningRegisterInfo() {
                projectDetail(this.$route.query.registerinfoId).then(response => {
                    if (response.data.code == '0') {
                        let planningRegisterInfo = response.data.data;
                        this.planningRegisterInfo = planningRegisterInfo;
                    }
                });
            },
            goBack() {
                this.$router.go(-1);
            },
            // 获取详情信息
            getDetailData() {
                projectDetail(this.$route.query.registerinfoId).then(response => {
                    this.getResultDetail(response);
                })
            },
            async getResultDetail(response) {

                if (response.data.code == '0') {
                    let records = response.data.data;
                    if (records.fileId != "" && records.fileId != null) {
                        this.multipleFiles = [];
                        this.multipleFiles = await this.getFileInfoPageTemp(records);
                    }
                    this.stageActive = stageMap[records.stage];
                    if ((records.planningRank == 'C' || records.planningRank == 'B') && records.stage == 'H') {
                        this.stageActive = 5;
                        this.cssbeian = true;
                    }

                    this.getDetailDataMins(records);
                    if (records.registerinfoTopicVOList.length > 0) {
                        this.msgFlag = true;
                        for (let i in records.registerinfoTopicVOList) {
                            this.getMessage(records.registerinfoTopicVOList[i], i);
                        }
                    }
                }
            },
            getFileInfoPageTemp(records) {
                return new Promise((resolve, reject) => {
                    if (records.fileId != "" && records.fileId != null) {
                        getfileinfopage(Object.assign({
                            current: 1,
                            size: 100,
                            fileIds: records.fileId
                        })).then(response => {
                            let multipleFiles = response.data.data.records;
                            resolve(multipleFiles);
                        }).catch(
                        )
                    }
                })
            },
            getMessage(obj, item) {
                //默认得到第一个数据
                if (item == 0) {
                    messagePage(Object.assign({
                        current: 1,
                        size: 10,
                        topicId: obj.topicId,
                        ascs: 'send_time'
                    })).then(response => {
                        if (response.data.code == 0) {
                            let record = response.data.data.records;
                            let pageTemp = {};
                            pageTemp.currentPage = response.data.data.current;
                            pageTemp.pageSize = response.data.data.size;
                            pageTemp.total = response.data.data.total;
                            this.topicActiveName = String(obj.topicId); //tabs默认显示第一个部门
                            this.topicIdTemp = obj.topicId;
                            this.pageTemp = pageTemp;

                            this.putList(record, obj.deptName, obj.topicId, this.pageTemp);
                        }
                    });
                } else {
                    let record = null;
                    this.putList(record, obj.deptName, obj.topicId, this.pageTemp);
                }

            },
            putList(record, deptName, topicId, pageTemp) {
                this.msgListTemp = [];

                if (record != null) {
                    this.recursive(record);    //递归消息放入消息列msgListTemp中
                }

                let msgMap = {
                    deptName: deptName,
                    msgDataList: this.msgListTemp,
                    topicId: topicId,
                    pageTemp: pageTemp,
                };
                if (record != null) {
                    this.msgDataListTemp = msgMap.msgDataList;
                }

                this.msgList.push(msgMap)
            },
            recursive(record, deptName) {
                for (let i in record) {
                    let flag = false;
                    if (record[i].senderId == this.userInfo.userId) {
                        flag = true
                    }
                    let msgDataMap = {
                        orgName: record[i].senderNickname,
                        nickName: record[i].senderNickname ? record[i].senderNickname.substring(0, 2) : '',
                        msgTime: record[i].sendTime,
                        msgContent: record[i].content,
                        replyFlag: flag,
                        senderId: record[i].senderId,
                        topicId: record[i].topicId,
                        messageId: record[i].messageId,
                        rightaway: record[i].parentId !== null ? 1 : 0,
                        fileId: record[i].fileId,
                        filenametemp: record[i].fileFullName,
                    };
                    this.msgListTemp.push(msgDataMap);
                    if (record[i].children !== null) { //当还有子消息时继续递归
                        this.recursive(record[i].children);
                    }
                }
            },
            //当点击显示第几页时触发
            onLoad(page) {
                this.currentTemp = page;
                messagePage(Object.assign({
                    current: page,// 当前页数
                    size: this.pageSizeTemp,// 每页显示多少条
                    topicId: this.topicIdTemp,
                    ascs: 'send_time'
                })).then(response => {
                    if (response.data.code == 0) {
                        let record = response.data.data.records;
                        this.putList(record);
                    }
                })
            },
            //当每页显示的条数改变时触发
            sizeChange(page) {
                messagePage(Object.assign({
                    current: 1,// 当前页数
                    size: page,// 每页显示多少条
                    topicId: this.topicIdTemp,
                    ascs: 'send_time'
                })).then(response => {
                    if (response.data.code == 0) {
                        let record = response.data.data.records;
                        this.putList(record);
                    }
                })
            },
            onLoadFortabs() {
                messagePage(Object.assign({
                    current: 1,// 当前页数
                    size: 10,// 每页显示多少条
                    topicId: this.topicIdTemp,
                    ascs: 'send_time'
                })).then(response => {
                    if (response.data.code == 0) {
                        let record = response.data.data.records;
                        this.pageTwo.currentPage = response.data.data.current;
                        this.pageTwo.pageSize = response.data.data.size;
                        this.pageTwo.total = response.data.data.total;
                        this.pageTemp = this.pageTwo;
                        this.putListForpage(record);
                    }
                })
            },

            putListForpage(record) {
                this.msgListTemp = [];
                if (record != null) {
                    this.recursive(record);    //递归消息放入消息列msgListTemp中
                }
                if (record != null) {
                    this.msgDataListTemp = this.msgListTemp;
                }
            },
            submitConfirm(validActionForm, stopLoading, closeDialog) {
                validActionForm((actionFormValid, object) => {
                    this.validateForm((valid) => {
                        if (valid && actionFormValid) {
                            let params = this.form;
                            taskComplete(this.taskId, params).then(response => {
                                if (response.data.code == 0) {
                                    this.$notify({
                                        title: '成功',
                                        message: '提交成功',
                                        type: 'success',
                                        duration: 2000
                                    });
                                    closeDialog();
                                    this.goBack();
                                }
                            }).finally(() => {
                                stopLoading();
                            });
                        } else {
                            this.formValidateErrorNotify();
                            stopLoading();
                        }
                    })
                });
            },
            formValidateErrorNotify() {
                this.$notify({
                    title: '错误',
                    message: '表单存在错误，请按提示修改',
                    type: 'error',
                    duration: 2000
                });
            },
            validateForm(callback) {
                if (this.$refs.form != null) {
                    this.$refs.form.validate((valid, object) => {
                        callback(valid, object);
                    });
                } else {
                    if (callback != null) {
                        callback(true);
                    }
                }
            },
        }
    }
</script>

<style lang="scss" scoped>
    .paginationcss {
        margin-top: 20px;
        float: right;
        margin-right: 28px;
    }
</style>
